在一個 C++ 程式宏大的劇場中,物件就像演員一樣。有些會全程留在舞台上,但大多數—— 區域物件——是只出現在單一場景中、瞬間消失的短暫存在。本課建立了一個基本區別:物件的 可見性 (範圍)與其 存在性 (生命週期)之間。
1. 語法範圍與執行生命週期
名稱的 範圍 是編譯時期的屬性:指程式碼中名稱可被使用的區域。相反地, 生命週期 是執行時期的屬性:指物件佔據實際記憶體位址的時間長度。
2. 自動物件
僅在區塊執行期間存在的物件稱為 自動物件。當控制流程經過其定義時(int n = 0;),並在遇到閉合括號(})時被銷毀。參數實質上是透過引數初始化的區域變數。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
When is an automatic object's memory typically reclaimed?
When the program finishes execution.
When the enclosing block (braces) terminates.
When the object is assigned a new value.
When the compiler optimizes the code.
✅ Correct!
Correct! Automatic objects are 'popped' from the stack the moment the function or block they are defined in ends.❌ Incorrect
The lifetime of an automatic object is strictly tied to the execution of the block where it is defined.QUESTION 2
True or False: A function's parameters have a lifetime that spans the entire program.
True
False
✅ Correct!
False is correct. Parameters are local variables; they are created when the function is called and destroyed when it returns.❌ Incorrect
Parameters are ephemeral. They only exist while the function is actively executing.QUESTION 3
Which code snippet demonstrates the creation of an automatic object?
static int count = 0;int val = 5; (inside a function)extern int globalVar;#define MAX 100✅ Correct!
Regular variables defined inside a function without the 'static' keyword are automatic objects.❌ Incorrect
'static' objects have a lifetime that persists for the entire program execution, not just the block.QUESTION 4
In the context of local scope, what does 'lexical' refer to?
The speed of the program execution.
The memory address on the stack.
The physical region of the source code text.
The dictionary of keywords in C++.
✅ Correct!
Lexical scope refers to the spatial region in the code file where a name is recognized.❌ Incorrect
Lexical scope is a compile-time property related to the 'text' of the code, not the runtime execution.QUESTION 5
What is the primary benefit of automatic objects?
They allow variables to be accessed from any function.
They ensure memory efficiency by reclaiming space automatically.
They prevent the use of headers.
They increase the binary size of the program.
✅ Correct!
By automatically cleaning up memory when a block ends, C++ avoids the overhead of manual management for temporary variables.❌ Incorrect
Automatic objects are local; their benefit is memory safety and isolation within functions.Deep Dive: Local Variable Architecture
Analysis of Scope and Writing Requirements
You are auditing a function designed to process string inputs. You must distinguish between the placeholders (parameters) and the actual data passed (arguments), while ensuring the memory for local processing doesn't leak. Consider the following definitions:
- Parameter: Variable in function signature.
- Argument: Value passed during call.
- Local: Defined in block.
- Static Local: Local scope, global lifetime.
Q
1. [Short Answer] What is the difference between a parameter and an argument? (Minimum 50 words required)
Solution:
A parameter is a formal variable declared in the function's header that acts as a placeholder for incoming data. In contrast, an argument is the actual value, variable, or expression supplied to the function during a call. When a function is invoked, the parameters are initialized using the values of the arguments. This distinction is vital because parameters are local automatic objects that exist only within the function's lifetime, whereas the arguments exist in the caller's scope and may persist long after the function returns. Understanding this helps prevent confusion regarding data ownership and side effects.
A parameter is a formal variable declared in the function's header that acts as a placeholder for incoming data. In contrast, an argument is the actual value, variable, or expression supplied to the function during a call. When a function is invoked, the parameters are initialized using the values of the arguments. This distinction is vital because parameters are local automatic objects that exist only within the function's lifetime, whereas the arguments exist in the caller's scope and may persist long after the function returns. Understanding this helps prevent confusion regarding data ownership and side effects.
Q
2. [Short Answer] Explain the differences between a parameter, a local variable, and a local static variable. Give an example of a function in which each might be useful.
Solution:
A parameter is initialized by arguments at the call site and represents input data. A local variable is defined inside a block for temporary processing and is destroyed upon block exit. A local static variable is defined in a block (local scope) but its lifetime persists across function calls (global lifetime). Example: In a `logTransaction(double amount)` function, `amount` is a parameter representing the specific data. `double tax = amount * 0.1;` is a local variable used for a one-time calculation. `static int callCount = 0;` is a local static variable used to track how many times the function has been executed across the entire program session.
A parameter is initialized by arguments at the call site and represents input data. A local variable is defined inside a block for temporary processing and is destroyed upon block exit. A local static variable is defined in a block (local scope) but its lifetime persists across function calls (global lifetime). Example: In a `logTransaction(double amount)` function, `amount` is a parameter representing the specific data. `double tax = amount * 0.1;` is a local variable used for a one-time calculation. `static int callCount = 0;` is a local static variable used to track how many times the function has been executed across the entire program session.
Q
3. [Writing Task] Write a main function that takes two arguments. Concatenate the supplied arguments and print the resulting string. (Minimum 30 words required)
Solution:
cpp int main(int argc, char* argv[]) { if (argc < 3) return 1; // We must check if two arguments were actually provided via the command line. std::string result = std::string(argv[1]) + std::string(argv[2]); std::cout << result << std::endl; return 0; } This implementation utilizes the `argc` parameter to verify that the user provided at least two arguments before attempting to concatenate and print the combined string result.
cpp int main(int argc, char* argv[]) { if (argc < 3) return 1; // We must check if two arguments were actually provided via the command line. std::string result = std::string(argv[1]) + std::string(argv[2]); std::cout << result << std::endl; return 0; } This implementation utilizes the `argc` parameter to verify that the user provided at least two arguments before attempting to concatenate and print the combined string result.
Q
4. [Writing Task] Exercise 6.22: Write a function to swap two int pointers.
Solution:
To swap the actual addresses stored in two pointers, we must pass the pointers by reference: cpp void swapPointers(int* &p1, int* &p2) { int* temp = p1; p1 = p2; p2 = temp; } By using a reference to a pointer (`int* &`), the function can modify the local pointers in the calling scope rather than just swapping local copies of the addresses.
To swap the actual addresses stored in two pointers, we must pass the pointers by reference: cpp void swapPointers(int* &p1, int* &p2) { int* temp = p1; p1 = p2; p2 = temp; } By using a reference to a pointer (`int* &`), the function can modify the local pointers in the calling scope rather than just swapping local copies of the addresses.